import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getPageTitle } from '@/utils/util'
import { hasPermission } from '@/utils/async-routes'

const whiteList = ['/login', '/403', '/404'] // no redirect whitelist

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  // 开启加载条
  NProgress.start()

  // 设置导航标题
  document.title = getPageTitle(to.meta.title)

  // 判断是否有 token
  const hasToken = store.getters.token

  if (hasToken) {
    // 已登录情况下不让进入登陆页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      let hasGetUserInfo = store.getters.userInfo
      // 判断是否拉取菜单
      if (!hasGetUserInfo || !store.getters.routes) {
        try {
          // 拉取用户信息
          hasGetUserInfo = await store.dispatch('manager/mineInfo')
          // 拉取权限菜单
          const asyncRoutes = await store.dispatch('permission/getAsyncRoutes')
          router.addRoutes(asyncRoutes)
          // 判断即将进入的页面是否需要权限
          if (to.meta && to.meta.authId) {
            if (hasPermission(to.meta.authId, hasGetUserInfo.role)) {
              next({ ...to, replace: true }) // 有权限
            } else {
              next({ path: '/403' }) // 没有权限 转403
              NProgress.done()
            }
          } else {
            next({ ...to, replace: true })
          }
        } catch (error) {
          await store.dispatch('manager/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        // 判断即将进入的页面是否需要权限
        if (to.meta && to.meta.authId) {
          if (hasPermission(to.meta.authId, hasGetUserInfo.role)) {
            next() // 有权限
          } else {
            next({ path: '/403' }) // 没有权限 转403
            NProgress.done()
          }
        } else {
          next()
        }
      }
    }
  } else {
    // 没有token 且即将进入的页面需要权限 则跳到登录页
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
